package com.mitgroup.dmrvs.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.mitgroup.dmrvs.R;
import com.mitgroup.dmrvs.utils.AppManager;
import com.mitgroup.dmrvs.utils.Base64;
import com.mitgroup.dmrvs.utils.Utils;
import com.mitgroup.dmrvs.webservice.WSClient;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.ByteArrayOutputStream;
import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PreferencesUtils;

public class DetectorActivity extends AppCompatActivity {
    private static final int MSG_UPLOAD = 1;
    private ProgressDialog progressDialog;
    private static final String BUNDLE_UPLOAD_SUCCESS = "upload_success";
    private static final String BUNDLE_UPLOAD_FAIL = "upload_fail";
    private static final String BUNDLE_LOCAL_ERROR = "local_error";
    private Intent intent;
    @BindView(R.id.btn_back)
    public Button btnBack;
    @OnClick(R.id.btn_back)
    public void onBack(View view) {
        this.finish();
    }
    @BindView(R.id.tv_user_name)
    public TextView tvUserName;
    @BindView(R.id.btn_nav01)
    public Button btnReceiveCar;
    @OnClick(R.id.btn_nav01)
    public void onReceiveCar(View view) {
        intent = new Intent(DetectorActivity.this,
                ReceiveCarActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav02)
    public Button btnDiagnose;
    @OnClick(R.id.btn_nav02)
    public void onDiagnose(View view) {
        intent = new Intent(DetectorActivity.this,
                CarDiagnoseActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav03)
    public Button btnSettings;
    @OnClick(R.id.btn_nav03)
    public void onSettings(View view) {
        intent = new Intent(DetectorActivity.this,
                SettingsActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.iv_quit)
    public Button quit;
    @OnClick(R.id.iv_quit)
    public void onQuit(View view) {
        Utils.Exit(this);
    }
    @BindView(R.id.btn_car_diagnose)
    public Button btnCarDiagnose;
    @BindView(R.id.btn_intake)
    public Button btnIntake;
    @BindView(R.id.btn_fuel)
    public Button btnFuel;
    @BindView(R.id.btn_twc)
    public Button btnTwc;
    @BindView(R.id.btn_ac)
    public Button btnAc;
    @OnClick({R.id.btn_intake,R.id.btn_fuel,R.id.btn_twc,R.id.btn_ac})
    public void onGoDetector(View view) {
        switch (view.getId()) {
            case R.id.btn_twc:
                intent = new Intent(DetectorActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "twc");
                startActivity(intent);
                this.finish();

                break;
            case R.id.btn_intake:
                intent = new Intent(DetectorActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "intake");
                startActivity(intent);
                this.finish();

                break;
            case R.id.btn_ac:
                intent = new Intent(DetectorActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "ac");
                startActivity(intent);
                this.finish();
                break;
            case R.id.btn_fuel:
                intent = new Intent(DetectorActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "fuel");
                startActivity(intent);
                this.finish();
                break;
        }
    }
    @BindView(R.id.iv_standard)
    public ImageView ivStandard;
    @BindView(R.id.iv_detector)
    public ImageView ivDetector;
    @OnClick(R.id.iv_detector)
    public void onDetector(View view) {
        intent = new Intent(DetectorActivity.this,
                USBCameraActivity.class);
        intent.putExtra("capture",decStr );
        startActivity(intent);
    }
    @BindView(R.id.tv_detector_title)
    public TextView tvDetectorTitle;
    @BindView(R.id.tv_detector_item)
    public TextView tvDetectorItem;
    @BindView(R.id.tv_detector_suggest)
    public TextView tvDetectorSuggest;
    @BindView(R.id.radioGroup1)
    public RadioGroup radioGroup1;
    @BindView( R.id.btn_submit_detector)
    public Button btnSubmitDetector;
    @OnClick(R.id.btn_submit_detector)
    public void onSubmitDetector(View view) {
        String carInfoId=PreferencesUtils.getString(DetectorActivity.this,"carInfoId");
        if(carInfoId!=null && !"".equals(carInfoId))
        {
            String picPath=Environment.getExternalStorageDirectory()+"/dmrvs/"+decStr+".jpg";
            String imgCnt=	getFileContent(picPath);
            uploadDetectorItem(carInfoId,decStr,detectorLevel,imgCnt);
        }
        else {
             Toast.makeText(DetectorActivity.this, "请先提交接车信息！",
                    Toast.LENGTH_SHORT).show();
        }

    }
    public String userId;
    public String decStr;
    public String detectorLevel="正常";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detector);
        ButterKnife.bind(this);
        initView();

    }
    private void initView() {
        AppManager.getAppManager().addActivity(this);
        userId = PreferencesUtils.getString(DetectorActivity.this, "userId");
        radioGroup1.setOnCheckedChangeListener(new GenderOnCheckedChangeListener());
        String userName = PreferencesUtils.getString(DetectorActivity.this, "userName");
        tvUserName.setText(userName);

        decStr=getIntent().getStringExtra("detector");
        if("intake".equals(decStr))
        {
            btnIntake.setBackgroundResource(R.drawable.sub_nav_active);
            btnIntake.setTextColor(Color.parseColor("#fa6c19"));
            tvDetectorTitle.setText("进气系统");
            tvDetectorItem.setText("节气门积炭：");
            ivStandard.setImageDrawable(getResources().getDrawable(R.drawable.intake));
        }
        else if("ac".equals(decStr))
        {
            btnAc.setBackgroundResource(R.drawable.sub_nav_active);
            btnAc.setTextColor(Color.parseColor("#fa6c19"));
            tvDetectorTitle.setText("空调系统");
            tvDetectorItem.setText("蒸发箱污染：");
            ivStandard.setImageDrawable(getResources().getDrawable(R.drawable.ac));
        }
        else if("fuel".equals(decStr))
        {
            btnFuel.setBackgroundResource(R.drawable.sub_nav_active);
            btnFuel.setTextColor(Color.parseColor("#fa6c19"));
            tvDetectorTitle.setText("燃油系统");
            tvDetectorItem.setText("燃烧室积炭：");
            ivStandard.setImageDrawable(getResources().getDrawable(R.drawable.fuel));
        }
        else if("twc".equals(decStr))
        {
            btnTwc.setBackgroundResource(R.drawable.sub_nav_active);
            btnTwc.setTextColor(Color.parseColor("#fa6c19"));
            tvDetectorTitle.setText("三元催化系统");
            tvDetectorItem.setText("排气/三元污垢：");
            ivStandard.setImageDrawable(getResources().getDrawable(R.drawable.twc));
        }
    }

    public  String getFileContent(String filePath) {

        String content = "";
        try {
            content=bitmapToString(filePath);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return content;
    }
    public  String bitmapToString(String filePath) {

        Bitmap bm = getSmallBitmap(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 60, baos);
        byte[] b = baos.toByteArray();
        if(b.length<1024*2)
        {
            return "";
        }
        else
        {
            return Base64.encodeBytes(b);
        }

    }
    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
//		options.inSampleSize = calculateInSampleSize(options, 480, 800);
        options.inSampleSize = calculateInSampleSize(options, 320, 240);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }
    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    private class GenderOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group,int checkedId){
            switch(checkedId){
                case R.id.radio1:
                    detectorLevel="正常";
                    if("intake".equals(decStr))
                    {
                        tvDetectorSuggest.setText("进气门状况良好，注意保持");
                    }
                    else if("ac".equals(decStr))
                    {
                        tvDetectorSuggest.setText("蒸发箱状况良好，注意保持");
                    }
                    else if("fuel".equals(decStr))
                    {
                        tvDetectorSuggest.setText("燃烧室状况良好，注意保持");
                    }
                    else if("twc".equals(decStr))
                    {
                        tvDetectorSuggest.setText("排气系统/三元催化状况良好，注意保持");
                    }
                    break;
                case R.id.radio2:
                    detectorLevel="轻度";
                    if("intake".equals(decStr))
                    {
                        tvDetectorSuggest.setText("进气门状况一般，建议清洗");
                    }
                    else if("ac".equals(decStr))
                    {
                        tvDetectorSuggest.setText("蒸发箱状况一般，建议清洗");
                    }
                    else if("fuel".equals(decStr))
                    {
                        tvDetectorSuggest.setText("燃烧室状况一般，建议清洗");
                    }
                    else if("twc".equals(decStr))
                    {
                        tvDetectorSuggest.setText("排气系统/三元催化状况一般，建议清洗");
                    }
                    break;
                case R.id.radio3:
                    detectorLevel="中度";
                    if("intake".equals(decStr))
                    {
                        tvDetectorSuggest.setText("进气门状况较差，强烈建议清洗");
                    }
                    else if("ac".equals(decStr))
                    {
                        tvDetectorSuggest.setText("蒸发箱状况较差，强烈建议清洗");
                    }
                    else if("fuel".equals(decStr))
                    {
                        tvDetectorSuggest.setText("燃烧室状况较差，强烈建议清洗");
                    }
                    else if("twc".equals(decStr))
                    {
                        tvDetectorSuggest.setText("排气系统/三元催化状况较差，强烈建议清洗");
                    }
                    break;
                case R.id.radio4:
                    detectorLevel="重度";
                    if("intake".equals(decStr))
                    {
                        tvDetectorSuggest.setText("进气门状况很差，必须清洗");
                    }
                    else if("ac".equals(decStr))
                    {
                        tvDetectorSuggest.setText("蒸发箱状况很差，必须清洗");
                    }
                    else if("fuel".equals(decStr))
                    {
                        tvDetectorSuggest.setText("燃烧室状况很差，必须清洗");
                    }
                    else if("twc".equals(decStr))
                    {
                        tvDetectorSuggest.setText("排气系统/三元催化状况很差，必须清洗");
                    }
                    break;
                case R.id.radio5:
                    detectorLevel="其他";
                    tvDetectorSuggest.setText("查找故障原因并修复");
                    break;
            }
        }

    }

    protected void onResume() {

        if(decStr!=null && !"".equals(decStr)) {
            String path = Environment.getExternalStorageDirectory() + "/dmrvs/";
            File file=null;
            if ("intake".equals(decStr)) {
                path += "intake.jpg";
                file=new File(path);
                if(file.exists()) {
                    try {

                        Uri uri = Uri.fromFile(file);
                        ivDetector.setBackgroundResource(0);
                        ivDetector.setImageDrawable(null);
                        ivDetector.setImageURI(uri);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                    tvDetectorItem.setText("节气门积炭：");

            } else if ("ac".equals(decStr)) {
                path += "ac.jpg";
                file=new File(path);
                if(file.exists()) {
                    try {
                        Uri uri = Uri.fromFile(file);
                        ivDetector.setBackgroundResource(0);
                        ivDetector.setImageDrawable(null);
                        ivDetector.setImageURI(uri);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                tvDetectorItem.setText("蒸发箱污染：");
            } else if ("fuel".equals(decStr)) {
                path += "fuel.jpg";
                file=new File(path);
                if(file.exists()) {
                    try {
                        Uri uri = Uri.fromFile(file);
                        ivDetector.setBackgroundResource(0);
                        ivDetector.setImageDrawable(null);
                        ivDetector.setImageURI(uri);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                tvDetectorItem.setText("燃烧室积炭：");
            } else if ("twc".equals(decStr)) {
                path += "twc.jpg";
                file=new File(path);
                if(file.exists()) {
                    try {
                        Uri uri = Uri.fromFile(new File(path));
                        ivDetector.setBackgroundResource(0);
                        ivDetector.setImageDrawable(null);
                        ivDetector.setImageURI(uri);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                tvDetectorItem.setText("排气/三元污垢：");
            }


        }
        super.onResume();
    }
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }

    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MSG_UPLOAD:
                    String key = msg.getData().keySet().iterator().next();
                    if (BUNDLE_UPLOAD_FAIL.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(DetectorActivity.this,
                                msg.getData().getString(BUNDLE_UPLOAD_FAIL),
                                Toast.LENGTH_LONG).show();
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(DetectorActivity.this, "服务器连接失败！",
                                Toast.LENGTH_SHORT).show();

                    }
                    else if (BUNDLE_UPLOAD_SUCCESS.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(DetectorActivity.this,
                                msg.getData().getString(BUNDLE_UPLOAD_SUCCESS),
                                Toast.LENGTH_LONG).show();
                        DetectorActivity.this.finish();
                        Intent intent = new Intent(DetectorActivity.this,
                                CarDiagnoseActivity.class);
                        startActivity(intent);

                    }
                    break;

                default:
                    break;
            }
            removeMessages(msg.what);

        }
    };
    protected void uploadDetectorItem(String carInfoId,String  detectorItem,String detectorLevel,String imgCnt)
    {

        if(Utils.isNetworkAvailable(DetectorActivity.this)==false)
        {
            Toast.makeText(DetectorActivity.this,"网络尚未连接，请连接网络！", Toast.LENGTH_SHORT).show();
            return;
        }

        final String []key={"carInfoId","detectorItem","detectorLevel","imgContent"};
        final String []value={carInfoId,detectorItem,detectorLevel,imgCnt};
        progressDialog = ProgressDialog.show(DetectorActivity.this,
                getResources().getString(R.string.notice), "正在提交检测...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bundle bundle = new Bundle();
                try {
                    String rs = WSClient.soapGetInfo("uploadDetectorLevel",key,value);
                    JSONTokener jsonTokener = new JSONTokener(rs);
                    JSONObject jsonObject = (JSONObject) jsonTokener
                            .nextValue();
                    String status = jsonObject.getString("status");
                    String content = jsonObject.get("content").toString();
                    if("1".equals(status))						{
                        bundle.putString(BUNDLE_UPLOAD_SUCCESS, "提交检测成功！");

                    }
                    else
                    {
                        bundle.putString(BUNDLE_UPLOAD_FAIL, "提交检测失败，请重试！");
                    }
                }
                catch (Exception e) {

                    bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                }
                Message msg = mHandler.obtainMessage();
                msg.what = MSG_UPLOAD;
                msg.setData(bundle);
                mHandler.sendMessage(msg);
            }
        }).start();
    }
}
